<template>
    <view class="w100  pl-30 pr-30 pb-30">
        <uni-card padding="0">
            <view class="inforClass">试卷信息:</view>
            <view class="w100 rowsb rowsm h-100 ">
                <view style="width: 25%" class="fs-28 col333 fw-b"><text style="color: red">*</text>实践课程: </view>
                <view class="paperName disabled-view">
                    <!-- {{ itemData.practiceType == 1 ? '劳动教育' : itemData.practiceType == 2 ? '职业素养' :
                        itemData.practiceType == 3 ? '应急安全' : itemData.practiceType == 4 ? '思政实践' : '创新创业' }} -->
                        {{ (questionTab.find(v => v.value == itemData.practiceType) || {}).text }}
                </view>
            </view>
            <view class="w100 rowsb rowsm h-100 ">
                <view style="width: 25%" class="fs-28 col333 fw-b"><text style="color: red">*</text>试卷名称：</view>
                <input style="flex: 1" class="paperName" placeholder="请输入试卷名称" placeholder-class="fs-24 col888"
                    v-model="itemData.name">
            </view>
            <view class="w100 rowsb rowsm h-100 ">
                <view style="width: 25%" class="fs-28 col333 fw-b"><text style="color: red">*</text>考试时长：</view>
                <input class="paperName" type="number" placeholder="请设置考试时长(分钟)" placeholder-class="fs-24 col888"
                    v-model.number="itemData.allTime">

            </view>
            <view class="w100 h-100 rows rowsm">
                <view style="width: 25%" class="fs-28 col333 fw-b"><text style="color: red">*</text>考试时间：</view>
                <uni-datetime-picker style="flex: 1" v-model="itemData.range" type="daterange" />
            </view>
        </uni-card>

        <uni-card padding="0">
            <view class="inforClass pt-20">面向对象</view>
            <view class="typeWarp pl-20 pr-20">
                <view class="practiceType border-botm">
                    <view class="fs-28 col333 fw-b"><text style="color: red">*</text>面向学院：</view>
                    <view class="option">
                        <g-picker v-model="proxyName" :columns="proxyList" @confirm="changeProxy"></g-picker>
                    </view>
                </view>
            </view>
            <view class="typeWarp pl-20 pr-20">
                <view class="practiceType border-botm">
                    <view class="fs-28 col333 fw-b"><text style="color: red">*</text>面向专业：</view>
                    <view class="option">
                        <g-picker v-model="prozyName" :columns="prozyList" @confirm="changeProzy"></g-picker>
                    </view>
                </view>
            </view>
            <view class="typeWarp pl-20 pr-20">
                <view class="practiceType border-botm">
                    <view class="fs-28 col333 fw-b"><text style="color: red">*</text>面向年级：</view>
                    <view class="option">
                        <g-picker v-model="pronjName" :columns="pronjList" @confirm="changePronj"></g-picker>
                    </view>
                </view>
            </view>
            <view class="typeWarp pl-20 pr-20">
                <view class="practiceType">
                    <view class="fs-28 col333 fw-b"><text style="color: red">*</text>面向班级：</view>
                    <view class="option">
                        <g-picker v-model="probjName" :columns="probjList" @confirm="changeProbj"></g-picker>
                    </view>
                </view>
            </view>
        </uni-card>
        <uni-card>
            <view class="inforClass">试题预览:</view>
            <view class="item" v-for="(item, index) in problemList" :key="index">
                <view class="fs-30 mt-20 mb-20 col333 u-border-top pt-16" style="display: flex">
                    {{ index + 1 }}. {{ item.type == 1 ? '单选题' : item.type == 2 ? '判断题' : '多选题' }}
                    ({{ item.type == 1 ? itemData.selectScore : item.type == 2 ? itemData.judgeScore :
                        itemData.multipleScore }}分)
                </view>
                <view class="contentClass" v-html="item.questionContent"></view>
                <view v-for="(it, index) in item.questionBankOptionList" :key="index">
                    <view class="answer" style="display: flex">
                        <view style="width: 9%;">
                            <view class="unchecked" :class="it.answer == 1 ? 'active' : ''"> {{ it.name }}</view>
                        </view>
                        <view class="ml-10" v-html="it.content"></view>
                    </view>
                </view>
                <view class="mb-20 mt-20 fs-26 mb-20">
                    <view style="display: flex;">
                        <view class="fs-28 mr-10"> 正确答案: </view>
                        <view> {{ item.answerList.join('、') }} </view>
                    </view>
                    <view style="display: flex;">
                        <view class="fs-28 mr-10" style="white-space: nowrap;"> 解析: </view>
                        <view v-html="item.answerAnalysis || '暂无解析'"></view>
                    </view>
                </view>
            </view>
        </uni-card>
        <view class="w100 rowsa rowsm mt-50 mb-20" style="bottom: 100rpx;">
            <view class="w-202 h-84 br-42 rowsc rowsm colfff"
                style="background: linear-gradient(to bottom,#ff4949,#ff4949);"
                v-if="permissions.find(v => v == '*:*:*') || permissions.find(v => v == 'project:paper:remove')"
                @click="deletBtn">删除
            </view>
            <view class="w-202 h-84 br-42 rowsc rowsm colfff"
                style="background: linear-gradient(to bottom,#64606b,#64606b);" @click="submit('保存')">保存</view>
            <view class="w-202 h-84 br-42 rowsc rowsm colfff"
                style="background: linear-gradient(to bottom,#4897FF,#4878FF);"
                v-if="permissions.find(v => v == '*:*:*') || permissions.find(v => v == 'project:paper:publish')"
                @click="submit('发布')">发布</view>
        </view>
    </view>
</template>
<script>
import { Base64 } from 'js-base64';
export default {
    data() {
        return {
            problemList: [],
            itemData: {},
            analyzeId: null,
            proxyList: [],
            proxyName: null,
            prozyList: [],
            prozyName: null,
            probjList: [],
            probjName: null,
            pronjList: [],
            pronjName: null,
            permissions: [],
            permissList: [],
            questionTab: [],
            oldProxy: null,
            oldProzy: null,
        }
    },
    onLoad(e) {
        if (uni.getStorageSync('flag') == 'teacher') {
            this.$tools.axiosFromToken('POST', 'sysUser/getById', {}, '加载中').then(res => {
                if (res.code != 200) return this.$tools.showtt(res.msg)
                let getAllInfo = { ...res.data, user: JSON.parse(Base64.decode(res.data.user)) }
                uni.setStorageSync('getInfo', getAllInfo);
                this.permissions = res.data.permissions.flat() || [];
            })
        }
        // this.permissList = uni.getStorageSync('getInfo').practiceTypes;
        // const typeMap = {
        //     1: { value: '1', text: '劳动教育' },
        //     2: { value: '2', text: '职业素养' },
        //     3: { value: '3', text: '应急安全' },
        //     4: { value: '4', text: '思政实践' },
        //     5: { value: '5', text: '创新创业' }
        // };

        // this.permissList.forEach(v => {
        //     if (typeMap[v]) {
        //         this.questionTab.push(typeMap[v]);
        //     }
        // });
        // this.permissions = uni.getStorageSync('getInfo').permissions.flat() || [];

        this.getTypeCongfigList();
        this.itemData = e.item ? JSON.parse(e.item) : null;
        this.itemData.range = [this.itemData.startTime.slice(0, 10), this.itemData.endTime.slice(0, 10)];
        this.analyzeId = this.itemData.id;
        this.getInfo();
        if (this.itemData) {
            this.getListProxy();
            this.getListPronj();
            this.getListProzy(this.itemData.faceXy.slice(','));
            this.getListProbj(this.itemData.faceZy.slice(','));
        }
    },
    created() { },
    methods: {
        getTypeCongfigList() {
            this.$tools.axiosFromToken('GET', 'project/practice/type/config/list?pageNum=1&pageSize=50', {}, '加载中').then(res => {
                if (res.code != 200) return this.$tools.showtt(res.msg)
                res.rows.forEach(item => {
                    this.questionTab.push({ text: item.name, value: item.id })
                })
            })
        },
        getInfo() {
            this.$tools.axiosFromToken('POST', 'teacher/test/paper/user/getTestPaperInfo', { id: this.analyzeId }, '加载中').then(res => {
                if (res.code != 200) return this.$tools.showtt(res.msg)
                this.problemList = res.data;
                this.problemList.forEach(item => {
                    item.answerList = [];
                    item.questionBankOptionList.forEach(it => {
                        if (it.answer == 1) {
                            item.answerList.push(it.name)
                        }
                    })
                })
            })
        },

        // 查询学院
        getListProxy() {
            this.$tools.axiosFromToken('GET', 'project/proxy/listTotal', {}, '加载中').then(res => {
                if (res.code != 200) return this.$tools.showtt(res.msg)
                const xyId = this.itemData.faceXy.split(',');
                res.rows.forEach(v => {
                    xyId.forEach(y => {
                        if (v.id == y) {
                            v.check = true;
                        }
                    })
                })
                this.proxyList = res.rows;
                if (res.rows.length > 0) {
                    this.proxyList.unshift({ name: '全部', id: 999999, check: false });
                }
            })
        },

        getListProzy(id) {
            const data = {};
            if (id) {
                data.xyIds = id;
            }
            this.$tools.axiosFromToken('GET', 'project/prozy/listTotal', data, '加载中').then(res => {
                if (res.code != 200) return this.$tools.showtt(res.msg)
                const zyId = this.itemData.faceZy.split(',');
                res.rows.forEach(v => {
                    zyId.forEach(y => {
                        if (v.id == y) {
                            v.check = true;
                        }
                    })
                })
                this.prozyList = res.rows;
                if (res.rows.length > 0) {
                    this.prozyList.unshift({ name: '全部', id: 99999999, check: false });
                }
            })
        },
        getListProbj(id) {
            let data = {};
            data.zyIds = id;
            data.njIds = this.itemData.faceNj;
            if (id == undefined && data.njIds == undefined) {
                data = {}
            }
            if (id && data.njIds == undefined) {
                data.zyIds = id;
                delete data.njIds;
            }
            if (id == undefined && data.njIds) {
                delete data.zyIds;
            }
            this.$tools.axiosFromToken('GET', 'project/probj/listTotal', data, '加载中').then(res => {
                if (res.code != 200) return this.$tools.showtt(res.msg)
                const bjId = this.itemData.faceBj.split(',');
                res.rows.forEach(v => {
                    bjId.forEach(y => {
                        if (v.id == y) {
                            v.check = true;
                        }
                    })
                })
                this.probjList = res.rows;
                if (res.rows.length > 0) {
                    this.probjList.unshift({ name: '全部', id: 9999999999, check: false });
                }
            })
        },

        getListPronj() {
            this.pronjList = [];
            this.$tools.axiosFromToken('GET', 'project/class/selectorForList', {}, '加载中').then(res => {
                if (res.code != 200) return this.$tools.showtt(res.msg)
                const njId = this.itemData.faceNj.split(',');
                res.rows.forEach(v => {
                    njId.forEach(y => {
                        if (v.name == y) {
                            v.check = true;
                        }
                    })
                })
                this.pronjList = res.rows;
                if (res.rows.length > 0) {
                    this.pronjList.unshift({ name: '全部', id: 999999999999, check: false });
                }
            })
        },

        changeProxy(x, y, z) {
            if (JSON.stringify(this.oldProxy) === JSON.stringify(y)) return;
            this.oldProxy = y;
            let allId = [];
            this.prozyList = [];
            this.probjList = [];
            if (y.find(v => v == 999999)) {
                this.proxyList.slice(1).forEach(id => allId.push(id.id))
            } else {
                allId = y;
            }
            this.itemData.faceXy = allId.join(",");
            if (allId.length > 0) {
                this.getListProzy(allId);
            }
        },
        changeProzy(x, y, z) {
            if (JSON.stringify(this.oldProzy) === JSON.stringify(y)) return;
            this.oldProzy = y;
            let allId = [];
            this.probjList = [];
            if (y.find(v => v == 99999999)) {
                this.prozyList.slice(1).forEach(id => allId.push(id.id))
            } else {
                allId = y;
            }
            this.itemData.faceZy = allId.join(",");
            if (allId.length > 0) {
                this.getListProbj(allId);
            }
        },
        changeProbj(x, y, z) {
            let allId = [];
            if (y.find(v => v == 9999999999)) {
                this.probjList.slice(1).forEach(id => allId.push(id.id))
            } else {
                allId = y;
            }
            this.itemData.faceBj = allId.join(",");
        },
        changePronj(x, y, z) {
            let allId = [];
            this.probjList = [];
            if (y.find(v => v == 999999999999)) {
                this.pronjList.slice(1).forEach(id => allId.push(id.name))
            } else {
                allId = z;
            }
            this.itemData.faceNj = allId.join(",");
            if (this.prozyList.length > 1) {
                let zyIdList = [];
                this.prozyList.slice(1).forEach(id => zyIdList.push(id.id))
                this.getListProbj(this.itemData.faceZy == '' ? zyIdList : this.itemData.faceZy.split(','));
            }
        },
        deletBtn() {
            uni.showModal({
                title: '确认删除',
                content: `是否删除该试卷,删除后学生无法查看试卷`,
                success: (res) => {
                    if (res.confirm) {
                        this.$tools.axiosFromToken('DELETE', `project/paper/${this.analyzeId}`, {}, '加载中').then(res => {
                            if (res.code != 200) return this.$tools.showtt(res.msg);
                            uni.navigateBack({
                                delta: 1
                            });
                        })
                    } else if (res.cancel) {
                        // 用户点击了“取消”
                        console.log('取消删除');
                    }
                }
            });
        },
        submit(type) {
            let data = JSON.parse(JSON.stringify(this.itemData));
            if (!data.faceXy) {
                let faceXy = [];
                this.proxyList.slice(1).forEach(id => faceXy.push(id.id))
                data.faceXy = faceXy.join(",");
            }
            if (!data.faceZy) {
                let faceZy = [];
                this.prozyList.slice(1).forEach(id => faceZy.push(id.id))
                data.faceZy = faceZy.join(",");
            }
            if (!data.faceBj) {
                let faceBj = [];
                this.probjList.slice(1).forEach(id => faceBj.push(id.id))
                data.faceBj = faceBj.join(",");
            }
            if (!data.faceNj) {
                let faceNj = [];
                this.pronjAddList.slice(1).forEach(id => faceNj.push(id.name))
                data.faceNj = faceNj.join(",");
            }
            if (!data.name) return this.$tools.showtt("试卷名称不得为空")
            if (!data.allTime) return this.$tools.showtt("考试时长不得为空或者0")

            if (!data.range || data.range.length == 0) return this.$tools.showtt("考试时间不得为空")
            if (this.probjList.length < 2) return this.$tools.showtt("暂无查询班级信息，请先添加班级!")
            if (!data.faceXy) return this.$tools.showtt("请选择学院")
            if (!data.faceZy) return this.$tools.showtt("请选择专业")
            if (!data.faceBj) return this.$tools.showtt("请选择班级")
            if (!data.faceNj) return this.$tools.showtt("请选择年级")
            data.startTime = this.itemData.range[0] + " 00:00:00"
            data.endTime = this.itemData.range[1] + " 23:59:59"
            if (type == '保存') {
                this.$tools.axiosFromToken('PUT', `project/paper`, { ...data }, '加载中').then(res => {
                    if (res.code != 200) return this.$tools.showtt(res.msg);
                    uni.navigateBack({
                        delta: 1
                    });
                    setTimeout(() => {
                        this.$tools.showtt('编辑成功');
                    }, 0);
                })
            } else {
                this.$tools.axiosFromToken('PUT', `project/paper`, { ...data, status: 1 }, '加载中').then(res => {
                    if (res.code != 200) return this.$tools.showtt(res.msg);
                    uni.navigateBack({
                        delta: 1
                    });
                    setTimeout(() => {
                        this.$tools.showtt('发布成功');
                    }, 0);
                })
            }
        }
    }
}
</script>
<style lang="scss">
page {
    background-color: #f4f5f7;
    padding-bottom: 10rpx;
}

::v-deep .uni-card {
    margin-left: 5px !important;
    margin-right: 5px !important;
    overflow: visible;
}

::v-deep .uni-card__content {
    color: #000 !important;
}

.answer {
    padding: 24rpx;
    background: #f4f8fb;
    margin-bottom: 40rpx;
    font-size: 26rpx;
    color: #333;
    border-radius: 20rpx;
}

.unchecked {
    width: 40rpx;
    height: 40rpx;
    border-radius: 50%;
    text-align: center;
    margin-right: 10rpx;
    line-height: 1;
    padding-top: 4px;
    border: 2rpx solid #ced1d5;
    color: #bebebe;
}

.active {
    background: #08c67f;
    border: 0;
    color: #fff;
}

.ellipsis-text {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 100%;
    display: inline-block;
}

.paperName {
    flex: 1;
    height: 34px;
    line-height: 34px;
    border-radius: 3px;
    text-align: left;
    padding: 0 5px !important;
    border: 1px solid #ededed;
}

::v-deep .uni-select {
    width: 100% !important;
}

::v-deep .uni-stat__select {
    width: 100% !important;
    padding: 0 !important;

    uni-view {
        width: 100% !important;
    }
}

::v-deep .uni-date__x-input {
    height: 32px !important;
}

.inforClass {
    font-size: 16px;
    font-weight: 700;
    display: flex;
    align-items: center;
    margin: 8px 0;
}

.inforClass::before {
    content: '';
    width: 5px;
    height: 20px;
    background-color: #007AFF;
    margin-right: 5px;
    display: inline-block;
}

.practiceType {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 90rpx;
}

.border-botm {
    border-bottom: 1px #f1f1f1 solid;
}

::v-deep .uni-select__input-box {
    min-height: 32px !important;
}

.contentClass {
    ::v-deep p {
        font-size: 16px;
        font-weight: 500 !important;
        padding-bottom: 5px;
    }
}

::v-deep .uni-date {
    .uni-date__icon-clear {
        top: -4px;
        right: -6px;
    }
}

.disabled-view {
    background-color: #f5f7fa;
    color: #bebebe;
    cursor: not-allowed;
}
</style>